﻿'
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2011
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
'

Imports System.Collections.Generic
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports DotNetNuke.Modules.Media.MediaController
Imports DotNetNuke.Services.FileSystem
Imports DotNetNuke.Security
Imports DotNetNuke.UI.Utilities.DNNClientAPI
Imports WillStrohl.API.oEmbed

Namespace DotNetNuke.Modules.Media

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' The EditImage PortalModuleBase is used to manage the Image
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' 	[lpointer]	31.10.2005	Moved Images to a separate Project
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Partial Public MustInherit Class EditMedia
        Inherits MediaModuleBase

#Region " Private Members "

        Protected p_isNew As Boolean = True
        Dim p_UseModuleSettings As String = Null.NullString
        Dim p_None As String = Null.NullString
        Dim p_Left As String = Null.NullString
        Dim p_Center As String = Null.NullString
        Dim p_Right As String = Null.NullString

        Dim p_SupportedMediaFileTypes As String = Null.NullString

        Private Const p_SupportedImage As String = "<img src=""/images/grant.gif"" alt=""{0}"" title=""{0}"" />"
        Private Const p_UnsupportedImage As String = "<img src=""/images/deny.gif"" alt=""{0}"" title=""{0}"" />"
        Private Const FILE_TYPES_CACHE_KEY As String = "Media-SupportedFileTypes"

#End Region

#Region " Properties "

        Private ReadOnly Property SupportedMediaFileTypes As String
            Get
                If Not String.IsNullOrEmpty(Me.p_SupportedMediaFileTypes) Then
                    Return Me.p_SupportedMediaFileTypes
                End If

                Me.p_SupportedMediaFileTypes = String.Concat(glbImageFileTypes, ",", MEDIA_FILE_TYPES)

                Return Me.p_SupportedMediaFileTypes
            End Get
        End Property

        Protected ReadOnly Property SupportedImage As String
            Get
                Return String.Format(p_SupportedImage, Me.GetLocalizedString("SupportedImage.Text"))
            End Get
        End Property

        Protected ReadOnly Property UnsupportedImage As String
            Get
                Return String.Format(p_UnsupportedImage, Me.GetLocalizedString("UnsupportedImage.Text"))
            End Get
        End Property

#End Region

#Region " Event Handlers "

        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                'EnableClientPersonalization("MediaModule", String.Concat("MediaModule-", Me.ModuleConfiguration.ModuleDefID), Me.Page)
                Framework.jQuery.RequestRegistration()

                'Get the IsNew state from the ViewState
                p_isNew = Convert.ToBoolean(ViewState("IsNew"))

                If Not Page.IsPostBack Then
                    Me.BindData()
                End If

                If Not Page.ClientScript.IsClientScriptBlockRegistered("jQuery-Plugin-qTip") Then
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType, "jQuery-Plugin-qTip", String.Concat("<script type=""text/javascript"" language=""javascript"" src=""", Me.ControlPath, "Scripts/qTip/jquery.qtip.min.js""></script>"))
                End If

                'Save the IsNew state to the ViewState
                ViewState("IsNew") = p_isNew

            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try

        End Sub

        ''' <summary>
        ''' cmdCancel_Click runs when the cancel button is clicked
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        Private Sub cmdCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdCancel.Click

            Me.SendBackToModule()

        End Sub

        ''' <summary>
        ''' cmdUpdate_Click runs when the update button is clicked
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdUpdate.Click

            If Page.IsValid Then
                Me.SaveMedia()
                Me.SendBackToModule()
            End If

        End Sub

        Private Sub cvMediaType_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvMediaType.ServerValidate

            Select Case Me.radMediaType.SelectedIndex
                Case 0
                    If String.IsNullOrEmpty(Me.ctlURL.Url) Then
                        args.IsValid = False
                    End If
                Case 1
                    If String.IsNullOrEmpty(Me.txtEmbed.Text) Then
                        args.IsValid = False
                    End If
                Case 2
                    If String.IsNullOrEmpty(Me.txtOEmbed.Text) Then
                        args.IsValid = False
                    End If
            End Select

        End Sub

        Private Sub radMediaType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radMediaType.SelectedIndexChanged
            Me.ToggleFileTypeView(Me.radMediaType.SelectedIndex)
        End Sub

        Private Sub lnkOEmbed_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkOEmbed.Click

            If Not String.IsNullOrEmpty(Me.txtOEmbed.Text) Then
                Dim ctlOEmbedProvider As New ProviderFormat
                If ctlOEmbedProvider.IsUrlSupported(Me.txtOEmbed.Text) Then
                    Me.lblOEmbedCheck.Text = String.Concat("<span class=""dnnmedia-okay"">", Me.GetLocalizedString("lblOEmbedCheck.Text.Supported"), "</span>")
                Else
                    Me.lblOEmbedCheck.Text = String.Concat("<span class=""dnnmedia-error"">", Me.GetLocalizedString("lblOEmbedCheck.Text.Unsupported"), "</span>")
                End If
            Else
                Me.lblOEmbedCheck.Text = String.Concat("<span class=""dnnmedia-error"">", Me.GetLocalizedString("lblOEmbedCheck.Text.EmptyString"), "</span>")
            End If

        End Sub

#End Region

#Region " Private Methods "

        Private Sub BindData()

            Me.LocalizeModule()

            ' Obtain a single row of text information
            Dim objMediaController As New MediaController
            Dim objMedia As MediaInfo = objMediaController.GetMedia(ModuleId)

            Me.BindControls()

            If Not objMedia Is Nothing AndAlso objMedia.ModuleID > Null.NullInteger Then
                With objMedia
                    p_isNew = False
                    Me.ddlImageAlignment.SelectedValue = .MediaAlignment.ToString
                    Me.ToggleFileTypeView(.MediaType)
                    Select Case .MediaType
                        Case 0 ' local file system
                            Me.ctlURL.Url = .Src
                        Case 1 ' embed code
                            Me.txtEmbed.Text = System.Web.HttpUtility.HtmlDecode(.Src)
                        Case 2 ' embedable url
                            Me.txtOEmbed.Text = .Src
                    End Select
                    Me.txtAlt.Text = .Alt
                    If .Width <> Null.NullInteger Then
                        Me.txtWidth.Text = .Width.ToString
                    End If
                    If .Height <> Null.NullInteger Then
                        Me.txtHeight.Text = .Height.ToString
                    End If
                    Me.ctlNavigateUrl.Url = .NavigateUrl
                    Me.ctlTracking.URL = .NavigateUrl
                    Me.ctlTracking.ModuleID = ModuleId
                    Me.chkAutoStart.Checked = objMedia.AutoStart
                    Me.chkLoop.Checked = objMedia.MediaLoop
                End With
            Else
                p_isNew = True
            End If

            ' populate the support file types in the UI
            Me.BindSupportedFileTypes()

        End Sub

        Private Sub BindControls()

            ' Load the Alignment list with localised values
            With ddlImageAlignment.Items
                .Add(New ListItem(p_UseModuleSettings, "0"))
                .Add(New ListItem(p_None, "1"))
                .Add(New ListItem(p_Left, "2"))
                .Add(New ListItem(p_Center, "3"))
                .Add(New ListItem(p_Right, "4"))
            End With

            ctlURL.FileFilter = String.Concat(glbImageFileTypes, ",", MEDIA_FILE_TYPES)
            With ctlNavigateUrl
                .ShowNewWindow = True
                .ShowTrack = True
                .ShowTabs = True
                .ShowFiles = True
            End With

            Me.ToggleFileTypeView(-1)

        End Sub

        Private Sub BindSupportedFileTypes()

            Dim collFiles As New List(Of FileTypeInfo)
            Dim objCache As Object = Services.Cache.CachingProvider.Instance().GetItem(FILE_TYPES_CACHE_KEY)

            If Not objCache Is Nothing Then
                collFiles = CType(objCache, List(Of FileTypeInfo))
            Else

                Dim arrModuleSupport As ICollection(Of String) = CType(Split(MEDIA_FILE_TYPES.Replace(".", String.Empty).Replace(" ", String.Empty), ","), ICollection(Of String))
                Dim arrHostSupport As ICollection(Of String) = CType(Split(SUPPORTED_MEDIA_FILE_TYPES, ","), ICollection(Of String))

                For Each oString As String In arrModuleSupport
                    Dim oFile As New FileTypeInfo
                    oFile.FileType = oString.ToLower
                    oFile.ModuleSupport = True
                    oFile.HostSupport = arrHostSupport.Contains(oString)
                    collFiles.Add(oFile)
                Next

                collFiles.Sort(Function(p1, p2) p1.FileType.CompareTo(p2.FileType))

                Services.Cache.CachingProvider.Instance().Insert(FILE_TYPES_CACHE_KEY, collFiles)

            End If

            Me.rptMediaFileTypes.DataSource = collFiles
            Me.rptMediaFileTypes.DataBind()

        End Sub

        Private Sub LocalizeModule()
            p_UseModuleSettings = Me.GetLocalizedString("UseModuleSettings.Text")
            p_None = Me.GetLocalizedString("None.Text")
            p_Left = Me.GetLocalizedString("Left.Text")
            p_Center = Me.GetLocalizedString("Center.Text")
            p_Right = Me.GetLocalizedString("Right.Text")

            Me.radMediaType.Items.Insert(0, New ListItem(Me.GetLocalizedString("radMediaType.Items.0"), "0"))
            Me.radMediaType.Items.Insert(1, New ListItem(Me.GetLocalizedString("radMediaType.Items.1"), "1"))
            Me.radMediaType.Items.Insert(2, New ListItem(Me.GetLocalizedString("radMediaType.Items.2"), "2"))

            Me.txtEmbed.Attributes("title") = Me.GetLocalizedString("plEmbed.Help")
            Me.txtOEmbed.Attributes("title") = Me.GetLocalizedString("plOEmbed.Help")
            Me.txtAlt.Attributes("title") = Me.GetLocalizedString("plAlt.Help")
            Me.txtWidth.Attributes("title") = Me.GetLocalizedString("plWidth.Help")
            Me.txtHeight.Attributes("title") = Me.GetLocalizedString("plHeight.Help")
            Me.ddlImageAlignment.Attributes("title") = Me.GetLocalizedString("plAlignment.Help")
            Me.chkAutoStart.Attributes("title") = Me.GetLocalizedString("lblAutoStart.Help")
            Me.chkLoop.Attributes("title") = Me.GetLocalizedString("lblLoop.Help")

            Me.valAltText.ErrorMessage = Me.GetLocalizedString("valAltText.ErrorMessage")
            Me.valHeight.ErrorMessage = Me.GetLocalizedString("valHeight.ErrorMessage")
            Me.valWidth.ErrorMessage = Me.GetLocalizedString("valWidth.ErrorMessage")
            Me.cvMediaType.ErrorMessage = Me.GetLocalizedString("valMediaType.ErrorMessage")

            Me.lnkOEmbed.Text = Me.GetLocalizedString("lnkOEmbed.Text")
        End Sub

        Private Sub SaveMedia()

            Dim objMediaController As New MediaController
            Dim objMedia As New MediaInfo

            Try
                ' Update settings in the database
                If Me.radMediaType.SelectedIndex = 0 Then ' standard file system
                    If String.Equals(ctlURL.UrlType, "F") Then
                        Dim ctlFiles As New FileController
                        Dim objFile As FileInfo = ctlFiles.GetFileById( _
                            Integer.Parse(Regex.Match(Me.ctlURL.Url, "\d+").Value, Globalization.NumberStyles.Integer), PortalId)
                        If Not objFile Is Nothing Then
                            If String.IsNullOrEmpty(Me.txtWidth.Text) Then
                                Me.txtWidth.Text = objFile.Width.ToString
                            End If
                            If String.IsNullOrEmpty(Me.txtHeight.Text) Then
                                Me.txtHeight.Text = objFile.Height.ToString
                            End If
                        End If
                    End If
                End If

                Dim sec As New PortalSecurity

                With objMedia
                    .ModuleID = ModuleId
                    .MediaType = Me.radMediaType.SelectedIndex
                    Select Case Me.radMediaType.SelectedIndex
                        Case 0 ' standard file system
                            .Src = sec.InputFilter(Me.ctlURL.Url, PortalSecurity.FilterFlag.NoScripting)
                        Case 1 ' embed code
                            .Src = sec.InputFilter(Me.txtEmbed.Text, PortalSecurity.FilterFlag.NoMarkup)
                        Case 2 ' oembed url
                            .Src = sec.InputFilter(Me.txtOEmbed.Text, PortalSecurity.FilterFlag.NoMarkup)
                    End Select
                    .Alt = sec.InputFilter(Me.txtAlt.Text, PortalSecurity.FilterFlag.NoMarkup)
                    If Not String.IsNullOrEmpty(Me.txtWidth.Text) Then
                        .Width = Integer.Parse(sec.InputFilter(Me.txtWidth.Text, PortalSecurity.FilterFlag.NoMarkup), Globalization.NumberStyles.Integer)
                    End If
                    If Not String.IsNullOrEmpty(Me.txtHeight.Text) Then
                        .Height = Integer.Parse(sec.InputFilter(Me.txtHeight.Text, PortalSecurity.FilterFlag.NoMarkup), Globalization.NumberStyles.Integer)
                    End If
                    .NavigateUrl = sec.InputFilter(Me.ctlNavigateUrl.Url, PortalSecurity.FilterFlag.NoMarkup)
                    .MediaAlignment = Integer.Parse(sec.InputFilter(Me.ddlImageAlignment.SelectedValue, PortalSecurity.FilterFlag.NoMarkup), Globalization.NumberStyles.Integer)
                    .AutoStart = Me.chkAutoStart.Checked
                    .MediaLoop = Me.chkLoop.Checked
                End With

                ' url tracking
                Dim objUrls As New UrlController
                objUrls.UpdateUrl(PortalId, Me.ctlNavigateUrl.Url, Me.ctlNavigateUrl.UrlType, Me.ctlNavigateUrl.Log, _
                    Me.ctlNavigateUrl.Track, ModuleId, Me.ctlNavigateUrl.NewWindow)

                ' add/update
                If p_isNew Then
                    objMediaController.AddMedia(objMedia)
                Else
                    objMediaController.UpdateMedia(objMedia)
                End If

            Catch exc As Exception    'Module failed to load
                LogException(exc)
                'ProcessModuleLoadException(Me, exc)
            End Try

        End Sub

        Private Sub SendBackToModule()

            Try
                Response.Redirect(NavigateURL(), True)
            Catch
                ' do nothing
            End Try

        End Sub

        Protected Function GetSupportedImage(ByVal oValue As Object) As String

            If Not oValue Is Nothing Then
                Dim strValue As String = oValue.ToString
                If String.Equals(strValue.ToLower, "true") Then
                    Return SupportedImage
                Else
                    Return UnsupportedImage
                End If
            Else
                Return UnsupportedImage
            End If

        End Function

        Private Sub ToggleFileTypeView(ByVal Selected As Integer)

            If Selected < 0 Or Selected > 2 Then
                Selected = 0
            End If

            Me.radMediaType.SelectedIndex = Selected

            Me.liFileSystem.Visible = (Selected = 0)
            Me.liEmbed.Visible = (Selected = 1)
            Me.liOEmbed.Visible = (Selected = 2)

        End Sub

#End Region

    End Class

End Namespace